﻿using Fluent;
using SLS.Document;
using SLS.ExClassLib.CLSOffice;
using SLS.ExClassLib.Events;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.OracleClient;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace SLS.Client
{
	/// <summary>
	/// 
	/// </summary>
    public partial class MainWindow
    {
        #region=========Property==========
        Hashtable myHashtable;
        private Process _process;
        private System.Windows.Forms.Panel _panel;
        public DataSet SetUser = new DataSet();
        public string ApplicationPath
        {
            get { return System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath); }
        }
        ExcelAgent exAgent;
        public DataSet dsParamaters = new DataSet("Paramaters");
        string filePath;
        public Dictionary<string, object> dicQueryParamater;
        Dictionary<string, object> dicParamater;
        public Dictionary<string, object> dicReportParamater = new Dictionary<string, object>();
        Dictionary<string, object> DicParaMaters = new Dictionary<string, object>();
        public string strUserName = "";
        public string strPassWord = "";
        public string strIntexSystem = "";
        public string strCompany = "";
        public string DocType = "";
        public string strExcelFile = "";
        public string strUser = "", strPwd = "";
        string OracleDBConnString = "user id=intex;data source=intex3;password=intex";
        public DataSet dsResult;
        private OracleConnection OracleDB;
        private OracleCommand orlReadCommand;
        string strOrdNum = ""; 
        Dictionary<string, object> resultSvcQuery = new Dictionary<string, object>();
        Dictionary<int, int> SizeQuantity = new Dictionary<int, int>();
        Dictionary<int, int> TTLSizeQuantity = new Dictionary<int, int>();
        public Dictionary<string, object> EnvExe = new Dictionary<string, object>();
        int SumOrderStyleColor = 0;
        int SumOrderStyleSize = 0;
        int OrderEndRow = 7;
        int OrderStartRow;
        string strPosition;
        string strLastOrdNum = "";
        string strABColor = "";
        string strLastABColor = "";
        int OrderColorStartRow = 0;
        string ABArticle = "";
        string ABColor = "";
        string StyleColorDes = "";
        string StyleDes = "";
        string strDelDate = "";
        int ABSize = 0;
        int singleQuantity = 0;
        int SizeCol = 0;
        double YarnQuantity = 0;
        int OrderColorGAAUFRowEnd = 0;
        int OrderSizeSumRow = 0;
        public ArrayList UserList = new ArrayList();
        DataTable tbFileList = null;
        #endregion
        #region =================INIT=================
        #region========CONTAINER===============
        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr SetParent(IntPtr hWndChild,
        IntPtr hWndNewParent);
        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr FindWindow(string lpClassName,
        string lpWindowName);
        [DllImport("user32.dll")]
        static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);

        [DllImport("user32.dll", SetLastError = true)]
        static extern int GetWindowLong(IntPtr hWnd, int nIndex);

        [DllImport("user32")]
        private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags);

        private const int SWP_NOZORDER = 0x0004;
        private const int SWP_NOACTIVATE = 0x0010;
        private const int GWL_STYLE = -16;
        private const int WS_CAPTION = 0x00C00000;
        private const int WS_THICKFRAME = 0x00040000;


        #endregion
        public void CanExecuteAllways(object sender, CanExecuteRoutedEventArgs e)
        {
            e.Handled = true;
            e.CanExecute = true;
        }

        private void CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.Handled = true;
            e.CanExecute = true;
        }

		#endregion

		#region =================COMMAMNDS=================
        private void themes_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                string theme = e.AddedItems[0].ToString();

                // Window Level
                // this.ApplyTheme(theme);

                // Application Level
                // Application.Current.ApplyTheme(theme);
            }
        }
        private void btnINTEX_Click(object sender, RoutedEventArgs e)
        {
            /*
            Process.Start(@"C:\intex.w\intex\work\Client.bat", "SUWTE");
            // Sleep the thread in order to let the Notepad start completely           
            Thread.Sleep(50);
            IntPtr hwnd=FindWindow("itcscw5","INTEX application");
            SetParent(hwnd, wndHelp.Handle);
            ProcessStartInfo psi = new ProcessStartInfo(@"C:\intex.w\intex\work\Client.bat", "NBPRD");
            //psi = new ProcessStartInfo(@"notepad.exe");
            _process = Process.Start(psi);
            SetParent(_process.MainWindowHandle, _panel.Handle);

            // remove control box 
            int style = GetWindowLong(_process.MainWindowHandle, GWL_STYLE);
            style = style & ~WS_CAPTION & ~WS_THICKFRAME;
            SetWindowLong(_process.MainWindowHandle, GWL_STYLE, style);

            // resize embedded application & refresh 
            ResizeEmbeddedApp();*/


        }
        private Dictionary<string, object> ReadConfig(Dictionary<string, object> env)
        {
            string strKey = "";
            string strValue = "";
            Dictionary<string, object> envNew = new Dictionary<string, object>();
            try
            {
                foreach (KeyValuePair<string, object> kv in env)
                {
                    strKey = kv.Key;
                    strValue = System.Configuration.ConfigurationManager.AppSettings[strKey];
                    envNew.Add(strKey, strValue);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return envNew;
        }
        private void Connect2DBMenu_Click(object sender, EventArgs e)
        {
            this.strIntexSystem = (string)EnvExe["dbSystem"];
            this.strUserName = (string)EnvExe["dbUser"];
            this.strPassWord = (string)EnvExe["dbPwd"];

            OracleDBConnString = "user id=" + this.strUserName
                    + ";data source=" + this.strIntexSystem
                    + ";password=" + this.strPassWord + ";Unicode=True;"
                       + "Persist Security Info=True;";
            if (OracleDB != null)
            {
                OracleDB.Close();
            }
            OracleDB = new OracleConnection(OracleDBConnString);
            OracleDB.ConnectionString = OracleDBConnString;
            dicParamater["OracleDB"] = OracleDB;
            dicParamater["OracleDBConnString"] = OracleDBConnString;
            string SqlServerDBConnString = "Data Source=192.168.5.2;Persist Security Info=True;Password=sasa;User ID=sa;";
            SqlConnection SqlServerDB = new SqlConnection(SqlServerDBConnString);
            dicParamater["SqlServerDB"] = SqlServerDB;
            dicParamater["SqlServerDBConnString"] = SqlServerDBConnString;
        }
        private void KillExcel()
        {
            Process[] AllProcesses = Process.GetProcessesByName("EXCEL");

            // check to kill the right process
            foreach (Process ExcelProcess in AllProcesses)
            {
                if (myHashtable.ContainsKey(ExcelProcess.Id) == false)
                    ExcelProcess.Kill();
            }

            AllProcesses = null;
        }
        private void CheckExcellProcesses()
        {
            Process[] AllProcesses = Process.GetProcessesByName("EXCEL");
            myHashtable = new Hashtable();
            int iCount = 0;

            foreach (Process ExcelProcess in AllProcesses)
            {
                myHashtable.Add(ExcelProcess.Id, iCount);
                iCount = iCount + 1;
            }
        }

        public void SetUpUserMenu(string company, string user)
        {
            DataTable umenu = SetUser.Tables["MENU" + user.Trim()];
            if (umenu == null)
                return;
            Control ct = null;
            foreach (DataRow dwUMenu in umenu.Rows)
            {
                string com = dwUMenu["COMPANY"].ToString().Trim();
                string proc = dwUMenu["PROCESS"].ToString().Trim();
                string menuitem = dwUMenu["MENUITEM"].ToString().Trim();
                string father = dwUMenu["FATHER"].ToString().Trim();
                if (com != company)
                    continue;
                if (proc == "VISIBLE")
                {
                    ct = (Control)this.FindName(menuitem);
                    if (ct != null)
                    {
                        ct.IsEnabled = true;
                        ct.Visibility = Visibility.Visible;
                    }
                    ct = (Control)this.FindName("t" + menuitem);
                    if (ct != null)
                    {
                        ct.IsEnabled = true;
                        ct.Visibility = Visibility.Visible;
                    }
                }
                if (proc == "MENU")
                {
                    Fluent.RibbonGroupBox cf = (Fluent.RibbonGroupBox)this.FindName(father);
                    if (cf != null)
                    {
                        cf.IsEnabled = true;
                        cf.Visibility = Visibility.Visible;
                    }
                    else
                    {
                        continue;
                    }
                    Fluent.Button cb = new Fluent.Button();
                    cb.Header = dwUMenu["HEADER"].ToString().Trim();
                    cb.Tag = dwUMenu["TAG"].ToString().Trim();
                    cb.Icon = dwUMenu["ICON"].ToString().Trim();
                    cb.LargeIcon = dwUMenu["LargeIcon"].ToString().Trim();
                    cb.SizeDefinition = "Large";

                    cb.Click += new RoutedEventHandler(btnReport_Click);
                    cf.Items.Add(cb);

                    TreeViewItem ctree = (TreeViewItem)this.FindName("t" + father);
                    if (ctree != null)
                    {
                        ctree.IsEnabled = true;
                        ctree.Visibility = Visibility.Visible;
                    }
                    else
                    {
                        continue;
                    }
                    TreeViewItem ctx = new TreeViewItem();
                    ctx.Header = dwUMenu["HEADER"].ToString().Trim();
                    ctx.Tag = dwUMenu["TAG"].ToString().Trim();
                    ctree.Items.Add(ctx);
                    //TreeViewItem
                }
            }
        }
        private void treeViewReport_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            try
            {
                if (((TreeViewItem)e.NewValue).Tag == null)
                    return;
                string doctype = ((TreeViewItem)e.NewValue).Tag.ToString();
                vm.ActivateReportByDocType(doctype);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        public DataSet ReSetSETUP(string company, string user)
        {
            DataSet setReturn = new DataSet();
            DataSet setResult = new DataSet();
            SetUser = new DataSet();
            DataSet settemp = new DataSet();
            try
            {
                ArrayList tables = new ArrayList();
                string fileroot = ApplicationPath + @"\Documents\";
                filePath = fileroot + "SETUP.xls";
                if (System.IO.File.Exists(filePath))
                {
                    if (exAgent == null)
                    {
                        exAgent = new ExcelAgent(filePath);
                    }
                    setResult = exAgent.LoadDataTableDef(filePath, "");
                    foreach (DataTable tbTemp in setResult.Tables)
                    {
                        string tbName = tbTemp.TableName;
                        settemp = new DataSet();
                        settemp.DataSetName = "SETUP";
                        settemp.Merge(tbTemp);
                        filePath = fileroot + tbName + ".XML";
                        if (System.IO.File.Exists(filePath))
                        {
                            System.IO.File.Delete(filePath);
                        }
                        settemp.WriteXml(filePath);
                    }
                }
                filePath = fileroot + company + "SETUP.xls";
                if (System.IO.File.Exists(filePath))
                {
                    setResult = exAgent.LoadDataTableDef(filePath, "");
                    foreach (DataTable tbTemp in setResult.Tables)
                    {
                        string tbName = tbTemp.TableName;
                        if (!tbName.StartsWith("MENU"))
                            continue;
                        settemp = new DataSet();
                        settemp.DataSetName = "SETUP";
                        settemp.Merge(tbTemp);
                        filePath = fileroot + tbName + ".XML";
                        if (System.IO.File.Exists(filePath))
                        {
                            System.IO.File.Delete(filePath);
                        }
                        settemp.WriteXml(filePath);
                    }
                }
                tables.Add("FUNCTION");
                tables.Add("MENU" + user.Trim());
                foreach (string tbname in tables)
                {
                    filePath = fileroot + tbname + ".XML";

                    if (System.IO.File.Exists(filePath))
                    {
                        setResult.ReadXml(filePath);
                        SetUser.Merge(setResult);
                    }
                }
                tbFileList = SetUser.Tables["FUNCTION"];
                exAgent.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return setReturn;
        }
        public DataSet LoadSetSETUP(string company, string user)
        {
            DataSet setReturn = new DataSet();
            DataSet setResult = new DataSet();
            SetUser = new DataSet();
            try
            {
                ArrayList tables = new ArrayList();
                string fileroot = ApplicationPath + @"\Documents\";
                tables.Add("FUNCTION");
                tables.Add("MENU" + user.Trim());
                foreach (string tbname in tables)
                {
                    filePath = fileroot + tbname + ".XML";
                    if (System.IO.File.Exists(filePath))
                    {
                        setResult = new DataSet();
                        setResult.ReadXml(filePath);
                        SetUser.Merge(setResult);
                    }
                }
                if (SetUser.Tables.Contains("FUNCTION"))
                {
                    tbFileList = SetUser.Tables["FUNCTION"];
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return setReturn;
        }
		private RoutedCommand _OpenSnapshotCmd = new RoutedCommand("OpenSnapshot", typeof(MainWindow));
		public RoutedCommand OpenSnapshotCommand
		{
			get { return _OpenSnapshotCmd; }
		}

		#endregion
        
        #region =================BUTTON COMMAMNDS------------- 
        private void btnReport_Click(object sender, RoutedEventArgs e)
        {
            Fluent.Button sd = sender as Fluent.Button;
            string doctype = sd.Tag.ToString();
            vm.ActivateReportByDocType(doctype);
        }

        private void btnFileSave_Click(object sender, RoutedEventArgs e)
        {
            Fluent.MenuItem sd = new Fluent.MenuItem();
            sd.Name = "OnFileSave";
            DocumentManagement.Instance.ActiveDocument.ActivateMenuItem(sd, null);
        }
        private void btnRecordNew_Click(object sender, RoutedEventArgs e)
        {
            Fluent.MenuItem sd = new Fluent.MenuItem();
            sd.Name = "OnFileNewRecord";
            DocumentManagement.Instance.ActiveDocument.ActivateMenuItem(sd, null);
        }
        private void btnListTable_Click(object sender, RoutedEventArgs e)
        {
            Fluent.MenuItem sd = new Fluent.MenuItem();
            sd.Name = "OnListTable";
            DocumentManagement.Instance.ActiveDocument.ActivateMenuItem(sd, null);

        }
        private void btnListByMGDKEY_Click(object sender, RoutedEventArgs e)
        {
            Fluent.MenuItem sd = new Fluent.MenuItem();
            sd.Name = "OnListByMGDKEY";
            DocumentManagement.Instance.ActiveDocument.ActivateMenuItem(sd, null);
        }
        private void btnEditEveryRecord_Click(object sender, RoutedEventArgs e)
        {
            Fluent.MenuItem sd = new Fluent.MenuItem();
            sd.Name = "OnEditEveryRecord";
            DocumentManagement.Instance.ActiveDocument.ActivateMenuItem(sd, null);
        }

      
        private void btnSingleEnd_Click(object sender, RoutedEventArgs e)
        {
            Fluent.MenuItem sd = new Fluent.MenuItem();
            sd.Name = "OnSingleEnd";
            DocumentManagement.Instance.ActiveDocument.ActivateMenuItem(sd, null);
        }
        private void btnUpload_Click(object sender, RoutedEventArgs e)
        {
            Fluent.MenuItem sd = new Fluent.MenuItem();
            sd.Name = "OnFileSave";
            DocumentManagement.Instance.ActiveDocument.ActivateMenuItem(sd, null);
        }
        private void btnReturnResult_Click(object sender, RoutedEventArgs e)
        {
            Fluent.MenuItem sd = new Fluent.MenuItem();
            sd.Name = "OnReturnResult";
            DocumentManagement.Instance.ActiveDocument.ActivateMenuItem(sd, null);
        }
        private void btnValidate_Click(object sender, RoutedEventArgs e)
        {
            Fluent.MenuItem sd = new Fluent.MenuItem();
            sd.Name = "OnValidateRecord";
            DocumentManagement.Instance.ActiveDocument.ActivateMenuItem(sd, null);
        }
        private void btnRecordCopy_Click(object sender, RoutedEventArgs e)
        {
            Fluent.MenuItem sd = new Fluent.MenuItem();
            sd.Name = "OnRecordCopy";
            DocumentManagement.Instance.ActiveDocument.ActivateMenuItem(sd, null);
        }
        private void btnCreateByQueryFinish_Click(object sender, RoutedEventArgs e)
        {
            Fluent.MenuItem sd = new Fluent.MenuItem();
            sd.Name = "OnCreateByQueryFinish";
            DocumentManagement.Instance.ActiveDocument.ActivateMenuItem(sd, null);
        }
        private void btnCloseDocument_Click(object sender, RoutedEventArgs e)
        {
            Fluent.MenuItem sd = new Fluent.MenuItem();
            sd.Name = "OnFileExit";
            DocumentManagement.Instance.ActiveDocument.ActivateMenuItem(sd, null);
        }
        #endregion
    }
} 
